<template>
  <div class="order-view">
    <!-- 顶部导航栏 -->
    <!--    <THeader />-->

    <div class="order-container" v-loading="loading">
      <div v-if="!orderData" class="no-data">
        未找到订单信息
      </div>

      <template v-else>
        <!-- 订单状态信息 -->
        <el-card class="order-status-box">
          <div class="status-header">
            <i class="el-icon-circle-check success-icon"></i>
            <div>
              <h2>交易成功</h2>
              <p class="secondary-text">订单已完成，感谢您的光顾！</p>
            </div>
          </div>

          <div class="status-info">
            <div class="info-item">
              <span class="label">订单号码：</span>
              <span>{{ orderData.order.id }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span>{{ formatTime(orderData.order.createTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付时间：</span>
              <span>{{ formatTime(orderData.order.updateTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">完成时间：</span>
              <span>{{ formatTime(orderData.order.updateTime) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 收货信息 -->
        <el-card class="shipping-box">
          <div class="section-header">
            <h3>收货信息</h3>
          </div>
          <div class="shipping-info">
            <div class="info-item">
              <span class="label">收货人：</span>
              <span>{{ orderData.address.receiver || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系方式：</span>
              <span>{{ orderData.address.phone || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">收货地址：</span>
              <span>{{ getAddressText(orderData.address) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 商品信息 -->
        <el-card>
          <div class="section-header">
            <h3>商品信息</h3>
          </div>

          <el-table :data="orderItems" class="product-table">
            <el-table-column width="80">
              <template #header>
                <span class="table-header">商品</span>
              </template>
              <template #default="scope">
                <div class="product-image">
                  <img :src="scope.row.image" alt="商品图片" v-if="scope.row.image">
                  <div v-else class="image-placeholder">
                    <span>暂无图片</span>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column min-width="200">
              <template #header>
                <span class="table-header">商品描述</span>
              </template>
              <template #default="scope">
                <div>
                  <h4 class="product-title">{{ scope.row.name }}</h4>
                  <div class="product-spec" v-if="scope.row.spec">规格：{{ scope.row.spec }}</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column width="120" align="center">
              <template #header>
                <span class="table-header">单价</span>
              </template>
              <template #default="scope">
                <div class="price">¥{{ scope.row.price.toFixed(2) }}</div>
              </template>
            </el-table-column>

            <el-table-column width="100" align="center">
              <template #header>
                <span class="table-header">数量</span>
              </template>
              <template #default="scope">
                <div class="quantity">x{{ scope.row.quantity }}</div>
              </template>
            </el-table-column>

            <el-table-column width="120" align="right">
              <template #header>
                <span class="table-header">小计</span>
              </template>
              <template #default="scope">
                <div class="subtotal">¥{{ scope.row.subtotal.toFixed(2) }}</div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 价格汇总 -->
        <el-card class="summary-box">
          <div class="price-item">
            <span class="label">商品总金额：</span>
            <span>¥{{ orderData.order.totalAmount }}</span>
          </div>
          <div class="price-item">
            <span class="label">运费：</span>
            <span>¥{{ 0 }}</span>
          </div>
          <!--          <div class="price-item discount">-->
          <!--            <span class="label">优惠：</span>-->
          <!--            <span>-¥{{ orderSummary.discount.toFixed(2) }}</span>-->
          <!--          </div>-->
          <div class="price-item total">
            <span class="label">实付款：</span>
            <span class="actual-price">¥{{ orderData.order.totalAmount }}</span>
          </div>
        </el-card>

        <!-- 订单操作 -->
        <div class="actions-box">
          <el-button plain size="medium" @click="goToOrderList">返回订单列表</el-button>
          <el-button plain size="medium">再次购买</el-button>
          <el-button size="medium" type="primary" >评价商品</el-button>
        </div>
      </template>
    </div>

    <!--    <TFooter />-->
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
// import THeader from '@/components/THeader.vue'
// import TFooter from '@/components/TFooter.vue'

const route = useRoute()
const router = useRouter()
const orderId = route.params.id || route.query.id
const loading = ref(false)
const orderData = ref(null)


// 订单商品数据（从后端获取）
const orderItems = computed(() => {
  if (!orderData.value || !orderData.value.orderDetails) return []

  return orderData.value.orderDetails.map(detail => {
    // 从 products 数组中找到对应的商品信息
    const product = orderData.value.products?.find(p => p.id === detail.productId) || {}

    return {
      id: detail.productId,
      image: product.image || null, // 如果后端有图片字段
      name: product.name || '商品名称',
      spec: detail.sku || product.sku || '默认规格',
// 修改此处，使用 priceBefore 而不是 price
      price: product.priceAfter || product.priceBefore || 0,
      quantity: detail.count,
      // 同样修改小计计算中的字段
      subtotal: (product.priceAfter || product.priceBefore || 0) * detail.count    }
  })
})

// 订单摘要（从后端获取）
// const orderSummary = computed(() => {
//   if (!orderData.value) {
//     return {
//       total: 0,
//       shipping: 0,
//       discount: 0,
//       actualPay: 0
//     }
//   }
//
//   // 计算商品总金额 - 基于订单详情计算
//   const total = orderData.value.orderDetails?.reduce((sum, detail) => {
//     // 使用 detail.price（订单详情中的实际价格）而不是 product.priceBefore
//     return sum + (detail.price || 0) * detail.count
//   }, 0) || 0
//
//   // 运费（示例逻辑，你可以根据实际情况调整）
//   const shipping = total > 199 ? 0 : 15
//
//   // 优惠（示例，从后端获取实际优惠信息）
//   const discount = orderData.value.discount || 0
//
//   return {
//     total: total,
//     shipping: shipping,
//     discount: discount,
//     actualPay: total + shipping - discount
//   }
// })

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  // 如果是时间戳，转换为日期对象
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 获取完整地址文本
// 获取完整地址文本
const getAddressText = (address) => {
  if (!address) return '地址信息不存在'
  return `${address.province || ''} ${address.city || ''} ${address.district || ''} ${address.detail || ''}`
}
// 获取订单详情
const fetchOrderDetails = async (id) => {
  if (!id) {
    ElMessage.error('订单号不存在')
    return
  }

  loading.value = true
  try {
    // 获取完整订单信息（包含订单详情和商品信息）
    const response = await axios.get(`/api/order/ordertb/get-full/${orderId}`)

    if (response.data) {
      orderData.value = response.data
      console.log('订单详情:', orderData.value)
    } else {
      ElMessage.error('未找到订单信息')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 返回订单列表
const goToOrderList = () => {
  router.push('/orders') // 假设有订单列表页面
}

// 组件挂载时获取订单数据
onMounted(() => {
  if (orderId) {
    fetchOrderDetails(orderId)
  } else {
    ElMessage.error('缺少订单号参数')
  }
})
</script>

<style scoped>
.order-view {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.order-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 15px;
}

.no-data {
  text-align: center;
  padding: 50px;
  color: #999;
  font-size: 16px;
}

/* 订单状态样式 */
.order-status-box {
  margin-bottom: 20px;
  border-top: 3px solid #ff5000;
}

.status-header {
  display: flex;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.success-icon {
  font-size: 50px;
  color: #67C23A;
  margin-right: 20px;
}

.status-info {
  padding: 20px 0;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.info-item {
  line-height: 28px;
}

.label {
  color: #999;
  display: inline-block;
  width: 80px;
  text-align: right;
}

/* 各部分样式 */
.section-header {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.shipping-box {
  margin-bottom: 20px;
}

/* 表格样式 */
.product-table {
  width: 100%;
  border: none;
}

.table-header {
  font-weight: bold;
}

.product-image {
  width: 70px;
  height: 70px;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-placeholder {
  color: #999;
  font-size: 12px;
}

.product-title {
  margin: 0;
  font-size: 14px;
  line-height: 1.4;
  color: #333;
}

.product-spec {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.price, .subtotal {
  font-weight: bold;
}

/* 价格汇总 */
.summary-box {
  margin-top: 20px;
  padding: 20px;
}

.price-item {
  text-align: right;
  padding: 5px 0;
}

.price-item.discount {
  color: #67C23A;
}

.price-item.total {
  font-size: 18px;
  padding-top: 10px;
  border-top: 1px solid #eee;
  margin-top: 10px;
}

.actual-price {
  color: #ff5000;
  font-weight: bold;
  font-size: 22px;
}

/* 操作按钮 */
.actions-box {
  margin-top: 30px;
  text-align: right;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.el-button {
  margin-left: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .status-info {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .label {
    width: auto;
    display: inline;
  }
}
</style>
